package com.panda.entity.po;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: panda
 * @Date: 2022-05-18 15:12
 * @Description: spring security，登陆用户实现类
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    // 增加用户权限表
    private List<String> permissions;

    // 不需要进行序列化，redis不序列化SimpleGrantedAuthority这个实现类型的对象
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;  // 存储权限信息

//    后台管理员专用构造方法封装有后台访问权限
    public LoginUser(User user, List<String> permissions){
        this.user = user;
        this.permissions = permissions;
    }

//  前台用户专用构造方法，不需要权限方法
    public LoginUser(User user){
        this.user = user;
    }

    // fixme 修改了普通用户跳过返回权限信息逻辑，待测试
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 普通用户不需要返回权限信息
        if (this.permissions == null) {
            return null;
        }

        // 优化：只做一次遍历封装权限信息
        if (authorities != null){
            return authorities;
        }
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPasswordHash();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
